package com.xb.shiro;

import com.xb.entity.Menu;
import com.xb.entity.Role;
import com.xb.entity.User;
import com.xb.service.IMenuService;
import com.xb.service.IRoleService;
import com.xb.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xbyan
 * @date 2023/7/6 17:03
 */
@Component
public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    IUserService iUserService;
    @Autowired
    IMenuService iMenuService;
    @Autowired
    IRoleService roleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        String email = principalCollection.getPrimaryPrincipal().toString();
        List<Menu> menus = iMenuService.selectMenuByEmail(email);
        List<String> perms = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getPerms() != null && !menu.getPerms().isEmpty()) {
                perms.add(menu.getPerms());
            }
        }
        List<Role> roles = roleService.selectAllRoleByEmail(email);
        List<String> rolesByEmail = new ArrayList<>();
        for (Role role : roles) {
            rolesByEmail.add(role.getRole());
        }
        simpleAuthorizationInfo.addStringPermissions(perms);
        simpleAuthorizationInfo.addRoles(rolesByEmail);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String email = authenticationToken.getPrincipal().toString();
        User user = iUserService.selectUserByEmail(email);
        if (user != null) {
            return new SimpleAuthenticationInfo(
                    authenticationToken.getPrincipal(),
                    user.getPassword(),
                    ByteSource.Util.bytes(user.getSalt().getBytes()),
                    email
            );

        }

        return null;
    }
}
